package com.example.plugin.util;

import android.os.Environment;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

//配置读写类，可用于保存插件本地数据
public class ConfigUtil {

    public static void writeInt(String path,String item,String key,int value){
        write(path,item,key,value+"");
    }

    public static void writeLong(String path,String item,String key,long value){
        write(path,item,key,value+"");
    }

    public static void writeBoolean(String path,String item,String key,boolean value){
        write(path,item,key,value+"");
    }

    public static int readInt(String path,String item,String key){
        try{
            return Integer.parseInt(read(path,item,key));
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    public static long readLong(String path,String item,String key){
        try{
            return Long.parseLong(read(path, item, key));
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    public static boolean readBoolean(String path,String item,String key){
        try{
            return (read(path,item,key)).equals("true");
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /***
     * 写配置
     * @param path 文件路径
     * @param item 配置项名称，
     * @param key 配置节名称，为空则删除配置项
     * @param value 写入值，为空则删除配置节
     */
    public static void write(String path,String item,String key,String value){
        try{
            if(TextUtils.isEmpty(path) || TextUtils.isEmpty(item)) return;
            path=getAbsolutePath(path);

            FileReader fileReader = new FileReader(path);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            StringBuilder sb=new StringBuilder();
            boolean match=false;
            String op_str="";
            line=bufferedReader.readLine();
            while (line!=null){
                String read_item=line;
                //更新配置项（删除、修改）
                if(line.equals("["+item+"]")){
                    match=true;
                    //找到当前配置项的所有内容
                    StringBuilder sb2=new StringBuilder();
                    StringBuilder sb3=new StringBuilder();
                    while ((line=bufferedReader.readLine())!=null){
                        if((line.startsWith("[") && line.endsWith("]"))){
                            break;
                        }
                        sb2.append(line);
                        sb2.append("\n");
                    }
                    String[] arr=sb2.toString().split("\n");
                    if(TextUtils.isEmpty(key)){
                        //删除配置项，不添加read_item
                    }else{
                        sb.append(read_item);
                        sb.append("\n");
                        //修改配置项
                        if(TextUtils.isEmpty(value)){
                            //删除配置节
                            for (int i=0;i<arr.length;i++){
                                if(!arr[i].startsWith(key+"=")){
                                    sb3.append(arr[i]);
                                    sb3.append("\n");
                                }
                            }
                            op_str=sb3.toString();
                            sb.append(op_str);
                        }else{
                            //修改或添加配置节
                            int index=-1;
                            for (int i=0;i<arr.length;i++){
                                if(arr[i].startsWith(key+"=")){
                                    //修改
                                    sb3.append(key+"="+value);
                                    index=i;
                                }else
                                    sb3.append(arr[i]);
                                sb3.append("\n");
                            }
                            if(index==-1){
                                //添加
                                sb3.append(key+"="+value);
                                sb3.append("\n");
                            }
                            op_str=sb3.toString();
                            sb.append(op_str);
                        }
                    }

                }else{
                    sb.append(read_item);
                    sb.append("\n");
                    line=bufferedReader.readLine();
                }
            }
            if(!match && !TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)){
                //添加配置项
                sb.append("["+item+"]");
                sb.append("\n");
                sb.append(key+"="+value);
                sb.append("\n");
            }

            FileWriter fileWriter=new FileWriter(path);
            BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
            bufferedWriter.write(sb.toString());//写入

            bufferedWriter.flush();
            bufferedWriter.close();
            bufferedReader.close();
            fileReader.close();
            fileWriter.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /***
     * 读配置
     * @param path 文件路径
     * @param item 配置项名称
     * @param key 配置节名称
     * @return
     */
    public static String read(String path,String item,String key){
        try{
            if(TextUtils.isEmpty(path) || TextUtils.isEmpty(item) || TextUtils.isEmpty(key)) return "";
            path=getAbsolutePath(path);

            FileReader fileReader = new FileReader(path);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            String ret="";
            while ((line=bufferedReader.readLine())!=null){
                if(line.equals("["+item+"]")){
                    //找到当前配置项的所有内容
                    StringBuilder sb2=new StringBuilder();
                    while ((line=bufferedReader.readLine())!=null){
                        if((line.startsWith("[") && line.endsWith("]")))
                            break;
                        sb2.append(line);
                        sb2.append("\n");
                    }
                    String[] arr=sb2.toString().split("\n");
                    for (int i=0;i<arr.length;i++){
                        if(arr[i].startsWith(key+"=")){
                            ret=arr[i].substring(arr[i].indexOf("=")+1,arr[i].length());
                            break;
                        }
                    }
                    break;
                }
            }
            bufferedReader.close();
            fileReader.close();
            return ret;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    /***
     * 获取所有配置项名称
     * @param path
     * @return
     */
    public static List<String> getItems(String path){
        try{
            if(TextUtils.isEmpty(path)) return null;
            path=getAbsolutePath(path);

            FileReader fileReader = new FileReader(path);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            List<String> list=new ArrayList<>();
            while ((line=bufferedReader.readLine())!=null){
                if(line.startsWith("[") && line.endsWith("]"))
                    list.add(line.substring(1,line.length()-1));
            }
            bufferedReader.close();
            fileReader.close();
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 获取所有配置节名称
     * @param path
     * @return
     */
    public static List<String> getKeys(String path,String item){
        try{
            if(TextUtils.isEmpty(path) || TextUtils.isEmpty(item)) return null;
            path=getAbsolutePath(path);

            FileReader fileReader = new FileReader(path);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            List<String> list=new ArrayList<>();
            while ((line=bufferedReader.readLine())!=null){
                if(line.equals("["+item+"]")){
                    //找到当前配置项的所有内容
                    while ((line=bufferedReader.readLine())!=null){
                        if((line.startsWith("[") && line.endsWith("]")))
                            break;
                        int index=line.indexOf("=");
                        if(index>-1)
                            list.add(line.substring(0,index));
                    }
                    break;
                }
            }
            bufferedReader.close();
            fileReader.close();
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private static String getAbsolutePath(String path){
        try{
            File file;
            String root = Environment.getExternalStorageDirectory().getAbsolutePath();
            //得到绝对路径
            if(!path.startsWith(root)){
                if(path.startsWith("/"))
                    path=root+path;
                else
                    path=root+"/"+path;
            }
            //如果文件夹不存在则创建
            String relative_path=path.replace(root+"/","");
            String pathArr[] = relative_path.split("/");
            String temp_path=root+"/";
            for (int i = 0; i < pathArr.length - 1; i++) {
                temp_path += pathArr[i] + "/";
                file = new File(temp_path);
                if (file.exists() == false)
                    file.mkdir();
            }
            file = new File(path);
            if (file.exists() == false)
                file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
        return path;
    }
}
